package com.hkx.smipleemps.dao;

import com.hkx.smipleemps.common.domain.Employee;
import com.hkx.smipleemps.common.utils.HibernateUtils;
import com.hkx.smipleemps.common.utils.PageInfo;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;

import java.util.List;

public class EmployeeDaoImpl implements EmployeeDao{
    public void  addEmployee(Employee employee){
        HibernateUtils.getSession().save(employee);
    }

    @Override
    public List<Employee> selectEmployees() {
        Session session = HibernateUtils.getSession();
        Criteria criteria = session.createCriteria(Employee.class);
        List<Employee> list = criteria.list();
        return list;
    }

    @Override
    public PageInfo<Employee> selectEmployeesPage(int pageNo, int pageSize) {
        PageInfo<Employee> rs = null;
        Session session = HibernateUtils.getSession();
        String hql4Count = "select count(e) from com.hkx.smipleemps.common.domain.Employee e";
        long countLong = (Long) session.createQuery(hql4Count).uniqueResult();
        int  count = (int) countLong;
        String hql = " from com.hkx.smipleemps.common.domain.Employee e ";
        Query query = session.createQuery(hql);
        query.setFirstResult((pageNo-1)*pageSize);
        query.setMaxResults(pageSize);
        List<Employee> list = query.list();
        rs= new PageInfo<>(pageNo,pageSize,count,list);
        return rs;
    }

    @Override
    public void deleteEmployee(int id) {
        HibernateUtils.getSession().delete(new Employee().setId(id));
    }

    @Override
    public Employee selectEmployeeById(int id) {
        return (Employee) HibernateUtils.getSession().get(Employee.class,id);
    }
}
